package com.ankicoo.file.service.impl;

import com.aliyun.oss.common.utils.StringUtils;
import com.ankicoo.file.entity.FileInfoPO;
import com.ankicoo.file.mapper.FileInfoMapper;
import com.ankicoo.file.service.FileInfoService;
import com.ankicoo.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


/**
 * Description: 文件信息处理
 *
 * @author : QCYANG
 * @date : 2021/7/15 18:06
 */
@Service
public class FileInfoServiceImpl implements FileInfoService {
    @Autowired
    private FileInfoMapper fileInfoMapper;
    @Autowired
    private FileService fileService;

    @Override
    public FileInfoPO findFileInfoBuId(Integer fileId) {
        return fileInfoMapper.selectByPrimaryKey(fileId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public FileInfoPO saveNewFile(MultipartFile multipartFile) {
        FileInfoPO fileInfo = new FileInfoPO();
        fileInfo.setFileName(multipartFile.getOriginalFilename());
        fileInfo.setFileSize(multipartFile.getSize());
        fileInfo.setContentType(multipartFile.getContentType());
        fileInfoMapper.insert(fileInfo);
        try {
            saveFile(fileInfo,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileInfo;
    }

    @Override
    public void saveFile(FileInfoPO fileInfo, InputStream inputStream) {
        String realPath = concatFilePath(fileInfo.getFileId(), fileInfo.getFileName(), fileInfo.getFileType());
        fileService.saveFile(realPath,inputStream);
    }

    @Override
    public InputStream openInputStream(Integer fileId){
        FileInfoPO info = findFileInfoBuId(fileId);
        String filePath = concatFilePath(fileId, info.getFileName(), info.getFileType());
        return fileService.openInputStream(filePath);
    }

    public void deleteFile(Integer fileId){
        FileInfoPO info = findFileInfoBuId(fileId);
        String filePath = concatFilePath(fileId, info.getFileName(), info.getFileType());
        fileService.deleteFile(filePath);
    }

    @Override
    public String concatFilePath(Integer fileId, String fileName, String fileType){
        String con = "/";
        String typeMenu = StringUtils.isNullOrEmpty(fileType)?"other":fileType;
        return fileId+con+typeMenu+con+fileName;
    }






}
